/* Copyright (c) 2009 SpringShowcase, Inc.
 * All right reserved.
 * http://code.google.com/p/springshowcase/
 * This software is the confidential and proprietary information of BeyondWeb
 * , Inc. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement
 * you entered into with BeyondWeb.
 *
 * Revision History
 * Author              Date             Description
 * ------------------   --------------    ------------------
 *  taeki.kim           2010. 3. 31.        
 */
package org.springshowcase.core.commons.utils;

import java.net.URLEncoder;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.util.UrlPathHelper;

/**
 * The Class WebUtil.
 * 
 * @author kim taeki
 * @version WebUtil.java//$Revision: 2838 $
 */
public class ControllerUtils {

	// ---------------------------------------------------------------------
	// Instance Variable
	// ---------------------------------------------------------------------

	/** The Constant logger. */
	private static final Logger logger = Logger
			.getLogger(ControllerUtils.class);

	// ---------------------------------------------------------------------
	// Constructors Methods
	// ---------------------------------------------------------------------

	// ---------------------------------------------------------------------
	// DI & set,get Methods
	// ---------------------------------------------------------------------

	// ---------------------------------------------------------------------
	// Interface Implement Methods
	// ---------------------------------------------------------------------

	// ---------------------------------------------------------------------
	// self Methods
	// ---------------------------------------------------------------------

	/**
	 * 호출 URL과 동일 위치로 이동한다.
	 * 
	 * @param request the request
	 * 
	 * @return the forward view
	 */
	public final static String getForwardView(HttpServletRequest request) {

		String forward = request.getServletPath();

		if (forward.lastIndexOf('.') > -1) {
			return StringUtils.trimToEmpty(forward.substring(0, forward
					.lastIndexOf('.')));
		}
		return "";
	}

	/**
	 * 호출 URL과 동일 위치로 이동한다.
	 * 
	 * @param request the request
	 * @param defaultValue the default value
	 * 
	 * @return the forward view
	 */
	public final static String getForwardView(HttpServletRequest request,
			String defaultValue) {

		String forward = request.getServletPath();

		if (forward.lastIndexOf('.') > -1) {
			return StringUtils.trimToEmpty(forward.substring(0, forward
					.lastIndexOf('.')));
		}
		return defaultValue;
	}

	/**
	 * 파라미터에 값에 의해서 페이지를 이동 한다.
	 * 
	 * @param defaultValue the default value
	 * 
	 * @return the forward view
	 */
	public final static String getForwardView(String defaultValue) {
		return defaultValue;
	}

	/**
	 * 파라미터 값이 존재 하지 않을겨우는 입력폼으로 생각하고 true값을 리턴 한다.
	 * 
	 * @param value the value
	 * 
	 * @return true, if is adds the form
	 */
	public final static boolean isAddForm(String value) {
		if (StringUtils.isEmpty(value)) {
			return true;
		}
		return false;
	}

	/**
	 * 배열 파라미터 값이 존재 하지 않을겨우는 입력폼으로 생각하고 true값을 리턴 한다.
	 * 
	 * @param values the values
	 * 
	 * @return true, if is adds the form
	 */
	public final static boolean isAddForm(String[] values) {
		boolean flag = false;

		if (values == null || values.length == 0) {
			return true;
		}

		for (int count = 0; count < values.length; count++) {
			if (isAddForm(values[count])) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	/**
	 * Url encoding.
	 * 
	 * @param url the url
	 * 
	 * @return the string
	 */
	public final static String urlEncoding(String url) {
		String str = StringUtils.trimToEmpty(url);

		if (url == null) {
			return null;
		}

		try {
			str = URLEncoder.encode(str, "utf-8");
		}
		catch (Exception e) {
			if (logger.isInfoEnabled()) {
				logger.warn(e);
			}
		}
		return str;
	}

	/**
	 * Gets the originating request uri.
	 * 
	 * @param request the request
	 * 
	 * @return the originating request uri
	 */
	public static String getOriginatingRequestUri(HttpServletRequest request) {
		UrlPathHelper uph;
		String url;
		String contextPath;

		uph = new UrlPathHelper();
		url = uph.getOriginatingRequestUri(request);
		contextPath = uph.getOriginatingContextPath(request);
		url = StringUtils.trimToEmpty(StringUtils.remove(url, contextPath));
		return url;
	}

	/**
	 * Gets the jS path for url.
	 * 
	 * @param request the request
	 * @param ext the ext
	 * @param prefix the prefix
	 * 
	 * @return the jS path for url
	 */
	public static String getJSPathForURL(HttpServletRequest request,
			String prefix, String ext) {
		String path = getOriginatingRequestUri(request);
		path = getContextName(request) + prefix;
		String urlPath = getOriginatingRequestUri(request);
		urlPath = urlPath.substring(0, urlPath.indexOf("."));
		path += urlPath + ext;
		return path;
	}

	/**
	 * Gets the context name.
	 * 
	 * @param context the context
	 * 
	 * @return the context name
	 */
	public final static String getContextName(HttpServletRequest request) {
		HttpSession session = request.getSession();
		ServletContext context = session.getServletContext();
		String value = context.getContextPath();

		if (!"/".equals(value)) {
			return value;
		}
		return "";
	}

	/**
	 * web.xml <listener>
	 * <listener-class>org.springframework.web.context.request
	 * .RequestContextListener</listener-class> </listener> Gets the current
	 * request.
	 * 
	 * @return the current request
	 */
	public static HttpServletRequest getCurrentRequest() {
		ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder
				.currentRequestAttributes();
		HttpServletRequest hsr = sra.getRequest();
		return hsr;
	}

	/**
	 * Gets the current locale.
	 * 
	 * @return the current locale
	 */
	public static Locale getCurrentLocale() {
		RequestContext rc = new RequestContext(getCurrentRequest());
		return rc.getLocale();
	}

	/**
	 * Gets the web application context for context loader listener.
	 * 
	 * @param request the request
	 * @return the web application context for context loader listener
	 * @throws Exception the exception
	 */
	public static WebApplicationContext getWebApplicationContextForContextLoaderListener(
			HttpServletRequest request) throws Exception {
		WebApplicationContext wac;
		ServletContext sc;
		HttpSession hs;
		hs = request.getSession();
		sc = hs.getServletContext();
		wac = WebApplicationContextUtils.getWebApplicationContext(sc);
		return wac;
	}

	/**
	 * Gets the bean.
	 *
	 * @param beanId the bean id
	 * @return the bean
	 * @throws Exception the exception
	 */
	public static Object getBean(String beanId) throws Exception {
		HttpServletRequest request = getCurrentRequest();
		WebApplicationContext wac = getWebApplicationContextForContextLoaderListener(request);
		return wac.getBean(beanId);
	}

	/**
	 * Gets the bean type.
	 *
	 * @param beanId the bean id
	 * @return the bean type
	 * @throws Exception the exception
	 */
	public static Class<?> getBeanType(String beanId) throws Exception {
		HttpServletRequest request = getCurrentRequest();
		WebApplicationContext wac = getWebApplicationContextForContextLoaderListener(request);
		return wac.getType(beanId);
	}
	
	/**
	 * Gets the web application context for dispatcher servlet.
	 * 
	 * @param request the request
	 * @return the web application context for dispatcher servlet
	 * @throws Exception the exception
	 */
	public static WebApplicationContext getWebApplicationContextForDispatcherServlet(
			HttpServletRequest request) throws Exception {
		return RequestContextUtils.getWebApplicationContext(request);
	}

}
